package controllers

import (
	"github.com/goravel/framework/contracts/http"
	"github.com/goravel/framework/facades"
	httpfacades "github.com/hulutech-web/http_result"
	"goravel/app/models"
	"goravel/app/services/emoji"
	"math/rand"
)

type MessageController struct {
	//Dependent services
	emoji emoji.EmojiService
}

func NewMessageController() *MessageController {
	return &MessageController{
		//Inject services
	}
}

func (r *MessageController) Index(ctx http.Context) http.Response {
	messages := []models.Message{}
	queries := ctx.Request().Queries()
	result, _ := httpfacades.NewResult(ctx).SearchByParams(queries).ResultPagination(&messages)
	return result
}

func (r *MessageController) Store(ctx http.Context) http.Response {
	var message models.Message
	ctx.Request().Bind(&message)
	if message.Text == "" {
		return httpfacades.NewResult(ctx).Error(http.StatusInternalServerError, "创建失败", nil)
	}
	if message.PrefixEmoji != "" {
		message.PrefixEmoji = string(r.emoji.Make())
	}
	if message.SuffixEmoji != "" {
		message.SuffixEmoji = string(r.emoji.Make())
	}
	if message.PrefixChar != "" {
		message.PrefixChar = string(generateRandomChar())
	}
	if message.SuffixChar != "" {
		message.SuffixChar = string(generateRandomChar())
	}
	if err := facades.Orm().Query().Model(&message).Create(&message); err != nil {
		return httpfacades.NewResult(ctx).Error(http.StatusInternalServerError, "创建失败", nil)
	}
	return httpfacades.NewResult(ctx).Success("创建成功", message)
}

func generateRandomChar() rune {
	r := rand.Intn(62) // 62 = 26 (a-z) + 26 (A-Z) + 10 (0-9)
	switch {
	case r < 26:
		return 'a' + rune(r) // 小写字母
	case r < 52:
		return 'A' + rune(r-26) // 大写字母
	default:
		return '0' + rune(r-52) // 数字
	}
}
